<?php
/**
 * 支付宝接口类
 */
class Alipay{
    var $dsql; 
    var $mid;
    var $furl = "/cart.php";
	var $surl = "/product.php";
    
    private $config = null;
    
    function __construct($pays){
    	 
    	$this->config = $pays;
    }
    
    public function cfg($key){
    	 
    	$rows = $this->config;
    	return $rows[$key];
    }

    /**
    * 生成支付代码
    * @param   array   $order      订单信息
    * @param   array   $payment    支付方式信息
    */
    function GetCode($order, $payment){
    	
    	//$payment  = $this->config;
        $real_method = $payment['alipay_pay_method'];
        switch ($real_method){
            case '0':
                $service = 'trade_create_by_buyer';
                break;
            case '1':
                $service = 'create_partner_trade_by_buyer';
                break;
            case '2':
                $service = 'create_direct_pay_by_user';
                break;
        }
        $agent = 'C4335994340215837114';
        $parameter = array(
          'agent'             => $payment['agent'],
          'service'           => $service,
          'partner'           => $payment['alipay_partner'],
          '_input_charset'    => "utf-8",
          'notify_url'        => $payment['notify_url'],
          'return_url'        => $payment['return_url'],
		  'cancel_url'        => $payment['cancel_url'],
          /* 业务参数 */
          'subject'           => "[".$payment['custom']."] orderno:".$order['out_trade_no'],
          'out_trade_no'      => $order['out_trade_no'],
          'price'             => 0.01,//$order['price']
          'quantity'          => 1,
          'payment_type'      => 1,
          /* 物流参数 */
          'logistics_type'    => 'EXPRESS',
          'logistics_fee'     => 0,
          'logistics_payment' => 'BUYER_PAY_AFTER_RECEIVE',
          /* 买卖双方信息 */
          'seller_email'      => $payment['alipay_account']
        );
        ksort($parameter);
        reset($parameter);
        $param = '';
        $sign  = '';
        foreach ($parameter AS $key => $val){
            $param .= "$key=" .urlencode($val). "&";
            $sign  .= "$key=$val&";
        }
        $param  = substr($param, 0, -1);
        $sign   = substr($sign, 0, -1). $payment['alipay_key'];
        $button = 'https://www.alipay.com/cooperate/gateway.do?'.$param. '&sign='.md5($sign).'&sign_type=MD5';
		return $button;
    }

    /**
     * 异步支付处理
     * @param  $order   订单信息
     * @param  $payment 支付方式信息
     */
    function notify($order, $payment){
    	F("alipay_notify",$payment);
    	//$payment = $this->config;
        if (!empty($_POST)){
            foreach($_POST as $key => $data){
                $_GET[$key] = $data;
            }
        }
        $orderno = trim($_GET['out_trade_no']);
        F("alipay_0_GET",$_GET);
        ksort($_GET);
        reset($_GET);
        $sign    = '';
        $filters = array("_visitid","_URL_","cateid","orderno","sign","sign_type","code","d");
        foreach ($_GET AS $key=>$val){
            if ( !in_array($key, $filters) ){
                $sign .= "$key=$val&";
				$config[$key] = $val;
            }
        }
		F("alipay_1_config",$config);

        $sign = substr($sign, 0, -1).$payment['alipay_key'];
		F("alipay_2_url",$sign);
		F("alipay_3_url",array("o"=>md5($sign),"s"=>$_GET['sign']));
		if (md5($sign) != $_GET['sign']){
			 $order['content']  = "[支付宝]交易签名没有通过";
			 $this->failure_db($order);
			 return false;
        }
        if($_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'WAIT_SELLER_SEND_GOODS' || $_GET['trade_status'] == 'TRADE_SUCCESS'){
        	$order['content']  = "[支付宝]交易支付成功";
        	$this->success_db($order);
			 return true;
        } else {
           $order['content']  = "[支付宝]交易支付失败";
		   $this->failure_db($order);
           return false;
       }
    }
	
	/**
	* 支付返回处理
	* @param $base 网站url根路劲
	* @param $s 成功提示信息
	* @param $f 失败提示信息
	* @return Array
	*/
	function return_url($base,$s,$f){

		if($this->notify()){
			$url = "window.location.href='".$base.$this->surl."';";
			$info ="succeed";
			$msg = $s;
		}else{
			$url = "window.location.href='".$base.$this->furl."';";
			$info ="error";
			$msg = $f;
		}
		return array("url"=>$url,"msg"=>$msg,"info"=>$info);
	}


    /**
     * 处理订单成功
     */
    function success_db($order){
    	
       $order['addtime'] = time();
       $order['status']  = 1;
       $model = M("OrderPay");
       $model->add($order);
       
       $where = array("orderno"=>$order['orderno']);
       M("Order")->where($where)->save(array("ispay"=>1));
       return $order['orderno'];
    }
	
    /**
     * 处理订单失败
     */
    function failure_db($order){
    	
       $order['addtime'] = time();
       $order['status']  = 1;
       $model = M("OrderPay");
       
       $model->add($order);
       return $order['orderno'];
    }

	function setReturnUrl($s,$f){
		$this->surl = $s;
		$this->furl = $f;
	}
}